: friend istream& operator >>(istream& is, TLine& line);
: protected:
: int PenSize;
: };
: Why are the two operator functions (<< and >>) declared as friends?
: Is it because the original declarations are not virtual and cannot be
: overridden? I understand that these function have to be modified
: because they deal with a user-defined type. But look at the
: definitions of the functions
These are operator functions not member functions so they can not be virtual!
: ostream&
: operator <<(ostream& os, const TLine& line)
: {
: // Write the number of points in the line
: os << line.GetItemsInContainer();
: // Write the pen size
: os << ' ' << line.PenSize;
: // Get an iterator for the array of points
: TPointsIterator j(line);
: // While the iterator is valid (i.e. we haven't run out of points)
: while(j)
: // Write the point from the iterator and increment the array.
: os << j++;
: os << '\n';
: // return the stream object
: return os;
: }
: istream&
: operator >>(istream& is, TLine& line)
: {
: unsigned numPoints;
: is >> numPoints;
// this one operates on numPoints which is unsigned so it uses the original >> definition
: is >> line.PenSize;
: while (numPoints--) {
: TPoint point;
: is >> point;
// operator >> should have been overloaded for TPoint class also
: line.Add(point);
: }
: // return the stream object
: return is;
: }
: This is the confusing part. How can the << and >> be used in the
: definitions of << and >>? Is seems like the new << and >> friend
: functions are just defining their own implementations for handling the
: user-defined type. This is overloading, isn't it?
the ones that are used inside the functions operate on ordinary data types i.e. unsigned so they use the original definitions of << and >>, the ones declared before. As you said this is overloading , but it is operator overloading. Operator functions are not members of any class, so they can not be declared virtual.
: I have, and am nearly finished with "The C++ Programming Language" by
: Bjarne Stroustrup. When I look at the friend function section he sayS
: that friends are used so that two classes can have functions in
: common. The function is able to access the private part of each
: class. But he says nothing about using a 'friend' declaration to do
: what this example is doing. Help?
Well this example is used so that the << and >> operator functions can access the private parts of the Tline class and the istream class. So he says something about what this example is doing using the friend declaration.
Learning C++ is a reality. So there are realities which even people dealing with Science fiction can not deal with. Another example is the reality of this poor guy, who has a 1.00 less CGPA then it could have been, as he likes reading Arthur C. Clarke especially during finals (the time period when I want to go to another galaxy)